package com.Servlet;

import com.DAO.UserDao;
import com.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebServlet("/userManagement")
public class UserServlet extends HttpServlet {
    private UserDao userDao;

    @Override
    public void init() throws ServletException {
    	userDao = new UserDao();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 设置字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");

        if ("delete".equals(action)){
            int id = Integer.parseInt(request.getParameter("id"));
            try {
                userDao.deleteUser(id);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("删除用户成功"+id);
            request.setAttribute("message", "删除用户成功");
            response.sendRedirect("userManagement");
        } else if ("edit".equals(action)){
            // 编辑用户
            int id = Integer.parseInt(request.getParameter("id"));
            User user = null;
            try {
                user = userDao.getUserById(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (user != null){
                //设置请求属性，使编辑页面显示数据
                request.setAttribute("id", user.getId());
                request.setAttribute("username", user.getUsername());
                request.setAttribute("password", user.getPassword());
                request.setAttribute("email", user.getEmail());
                request.getRequestDispatcher("editUser.jsp").forward(request, response);

            }
            /*request.setAttribute("user", user);
            request.getRequestDispatcher("editUser.jsp").forward(request, response);*/
        }else {
            //获取所有用户并展示
            List<User> users = null;
            try {
                users = userDao.getAllUsers();
                System.out.println("查询到的数量: " + users.size()); // 打印查询到的成绩数量
            } catch (Exception e) {
                e.printStackTrace();  // 打印异常
                throw new RuntimeException(e);
            }
            request.setAttribute("users", users);
            request.getRequestDispatcher("userManagement.jsp").forward(request, response);
        }



    }
}
